// pages/home/index.js
import requestUtil from '../../baseRequest'
import urls from '../../requestUrl'
import {
    orderProcess,
    insuranceStatus,
    accidentStatus
} from '../../utils/commons'
import commonUtils from '../../utils/util.js'

let openid = getApp().getUserOpenid()
let DEFAULT_PAGE = 1
let DEFAULT_SIZE = 10

Page({

    /**
     * 页面的初始数据
     */
    data: {
        testShow: false,
        spinShow: false,
        openid: openid,
        imgUrls: [],
        currentTab: 'tab4',
        menuList: [
            // {
            //     title: '救援\n工单',
            //     icon: '/assets/icon-leader.png',
            //     url: '/pages/workOrder/createOrder/index',
            // },
            {
                title: '运输\n工单',
                icon: '/assets/ysgd.png',
                url: '/pages/transportConfirm/stepOne/index',
            },
            {
                title: '运输仲裁\n申诉窗口',
                icon: '/assets/zcss.png',
                url: '/pages/arbitration/select/index'
            },
            // {
            //     title: '购买司机\n责任服务',
            //     icon: '/assets/icon-driver.png',
            //     url: '/pages/insurance/orderCreate/index?type=2',
            //     type: 2,
            // },
            // {
            //     title: '购买货物\n责任服务',
            //     icon: '/assets/icon-car.png',
            //     url: '/pages/insurance/orderCreate/index?type=0',
            //     type: 0
            // },
            // {
            //     title: '购买乘客\n责任服务',
            //     icon: '/assets/icon-user.png',
            //     url: '/pages/insurance/orderCreate/index?type=1',
            //     type: 1
            // },
            // {
            //     title: '车险询价',
            //     icon: '/assets/icon-chat.png',
            //     url: '/pages/enquiry/request/index'
            // },
            // {
            //     title: '事故受理窗口',
            //     icon: '/assets/icon-tel.png',
            //     url: '/pages/accidentReport/reportOrderSelect/index'
            // },
            {
                title: '申诉\n提交',
                icon: '/assets/sstj.png',
                url: '/subpackage/pages/complaint/add'
            },
            {
                title: '交通事故\n医疗垫付',
                icon: '/assets/yldf.png',
                url: '/subpackage/pages/relief/index'
            },
            // {
            //     title: '用户注册\n会员卡',
            //     icon: '/assets/yldf.png',
            //     url: '/subpackage/pages/userRegisterV2/index'
            // },
            {
                title: '加油优惠',
                icon: '/assets/yldf.png',
                url: '/subpackage/pages/tuanOil/stationList'
            },
            {
                title: '',
                icon: '',
                url: ''
            },
        ],
        orderTags: [{
                value: '-2',
                name: '进行中的工单',
                checked: true,
                color: 'blue'
            },
            {
                value: '-1',
                name: '已完成的工单',
                checked: false,
                color: 'blue'
            }
        ],
        orderCurrentTag: '-2',
        insuranceTags: [{
                name: '进行中',
                checked: true,
                color: 'blue'
            },
            {
                name: '已完成',
                checked: false,
                color: 'blue'
            },
            {
                name: '乘客险',
                checked: true,
                color: 'green'
            },
            {
                name: '货物险',
                checked: false,
                color: 'green'
            }
        ],
        accidentTags: [{
                name: '进行中',
                checked: true,
                color: 'blue'
            },
            {
                name: '已完成',
                checked: false,
                color: 'blue'
            },
            {
                name: '乘客险',
                checked: true,
                color: 'green'
            },
            {
                name: '货物险',
                checked: false,
                color: 'green'
            }
        ],
        taskList: [],
        orderProcess: orderProcess,
        insuranceOrderStatusList: insuranceStatus,
        insuranceList: [],
        accidentList: [],
        orderList: [],
        accidentStatusList: accidentStatus,
        insuranceListQuery: ['4', '6'],
        accidentListQuery: ['0', '1', '2'],
        transportConfirmList: [],
        transportConfirmUrl: {
            "complete": "/pages/transportConfirm/complete/index?id=",
            "detail": "/pages/transportConfirm/detail/index?id="
        },
        arbitrationUrl: '/pages/arbitration/detail/index?id=',
        transportConfirmListCount: 0,
        complaintOrderList:[],
        pageDto: {
            pageSize: 20,
            pageNum: 1,
            total: 0
        }
    },

    /**处理菜单点击事件 */
    handleClickMenuItem(e) {
        this.checkUserInfoRole(() => {
            if (!this.data.openid) {
                this.setData({
                    spinShow: true
                })
                setTimeout(() => {
                    let openid = getApp().getUserOpenid()
                    this.setData({
                        openid
                    })
                    this.handleClickMenuItem(e)
                }, 1000)
            } else {
                this.setData({
                    spinShow: false
                })
                const type = e.currentTarget.dataset.type
                let _url = e.currentTarget.dataset.url
                if (type === undefined) {
                    wx.navigateTo({
                        url: _url
                    })
                    return;
                }
                let insuranceType = getApp().globalData.insuranceTypes[type].id
                console.log(e)
                const param = {
                    openid: this.data.openid,
                    classifyId: insuranceType
                };
                requestUtil.postRequest(urls.workOrder.verify, param, (res) => {
                    console.log(res)
                    if (res) {
                        wx.navigateTo({
                            url: _url
                        })
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: '您所属的行业不能购买此服务',
                            showCancel: false
                        })
                    }
                }, () => {})
            }
        })
    },

    /**
     * 监听切换选项卡
     */
    handleTabChange({
        detail = {}
    }) {
        console.log('handleTabChange', detail)
        let d = {}
        d.currentTab = detail.key
        this.setData(d)
        if (detail.key == 'tab1' && this.data.orderList.length === 0) {
            this.getWorkOrderList()
        }
        if (detail.key == 'tab2' && this.data.insuranceList.length === 0) {
            this.data.insuranceListQuery = ['4', '6']
            this.getInsuranceOrderList(this.data.insuranceListQuery, '')
        }
        if (detail.key == 'tab3' && this.data.accidentList.length === 0) {
            this.getAccidentReportList()
        }
        if (detail.key == 'tab4' && this.data.transportConfirmList.length === 0) {
            this.getTransportConfirmList(0)
        }
        if (detail.key === 'tab6') {
            this.getRescueApplyOrderList();
        }
        if (detail.key === 'tab7') {
            this.getComplaintOrderList();
        }
        this.setData({
            pageDto: {
                pageSize: 20,
                pageNum: 1,
                total: 0
            }
        })
    },
    getComplaintOrderList() {
        const formData = {
            openId: wx.getStorageSync('openid'),
            criteria: {},
            pageDto: {
                ...this.data.pageDto
            }
        };
        requestUtil.postRequest(urls.complaint.getMiniAppPage, formData, (res) => {
            console.log(res);
            if (!res.hasError) {
                let orderList = [];
                const dataList = res.list;
                for (let i = 0; i < dataList.length; i++) {
                    orderList.push({
                        ...dataList[i],
                        createdDate: commonUtils.formatDate(dataList[i].createdDate, 'yyyy-MM-dd'),
                    })
                }
                this.setData({
                    complaintOrderList:orderList,
                    pageDto: {
                        ...this.data.pageDto,
                        total: res.total
                    }
                })
            }
        })

    },
    showComplaintDetail(event){
        let orderId = event.currentTarget.dataset.orderid;
        wx.navigateTo({
            url: '/subpackage/pages/complaint/detail?orderId=' + orderId,
        })
    },
    getRescueApplyOrderList() {
        const formData = {
            openId: wx.getStorageSync('openid'),
            criteria: {},
            pageDto: {
                pageSize: 99,
                pageNum: 1,
                total: 0
            }
        };
        requestUtil.postRequest(urls.rescueApply.getPage, formData, (res) => {
            const dataList = res.list;
            if (!res.hasError) {
                let orderList = [];
                for (let i = 0; i < dataList.length; i++) {
                    orderList.push({
                        ...dataList[i],
                        applyDate: commonUtils.formatDate(dataList[i].applyDate, 'yyyy-MM-dd'),
                    })
                }
                this.setData({
                    orderList,
                })
            }
        })
    },
    showDetail(event) {
        let orderId = event.currentTarget.dataset.orderid;
        wx.navigateTo({
            url: '/subpackage/pages/relief/detail?orderId=' + orderId,
        })
    },
    /**
     * 监听切换工单标签
     */
    onOrderTagChange(event) {
        console.log('!!!!!', event.detail.index)
        this.data.orderCurrentTag = event.detail.index === 0 ? '-2' : '-1'
        this.getWorkOrderList()
        return
    },

    /**点击创建工单按钮 */
    // createWorkOrder() {
    //     this.checkUserInfoRole(() => {
    //         wx.navigateTo({
    //             url: '/pages/workOrder/createOrder/index'
    //         })
    //     })
    // },
    /**点击运输责任单按钮 */
    createTransportConfirm() {
        this.checkUserInfoRole(() => {
            wx.navigateTo({
                url: '/pages/transportConfirm/stepOne/index'
            })
        })
    },
    /**点击运输责任单按钮 */
    createArbitration() {
        this.checkUserInfoRole(() => {
            wx.navigateTo({
                //url: '/pages/arbitration/create/index'
                url: '/pages/arbitration/detail/index?id=3b257a3000354b94b810443169001ed9'
            })
        })
    },
    /**权限拦截 */
    checkUserInfoRole(callback) {
        if (!this.data.userInfo) {
          setTimeout(() => {
            this.getUserInfo();
            this.checkUserInfoRole(callback);
          }, 100)
        } else {
          let userInfo = getApp().globalData.userInfo;
          this.setData({
            userInfo,
          })
          console.log({'userInfo':this.data.userInfo})
          if (this.data.userInfo) {
            const {userInfo} = this.data;
              if(userInfo.isMember && parseInt(userInfo.isMember)===0){
                //未获取微信授权的情况
                wx.showModal({
                  title: '温馨提示',
                  content: '您还未完成注册，请完成注册后重试',
                  confirmText: '前往注册',
                  success: res => {
                    if (res.confirm) {
                      wx.switchTab({
                        url: '/pages/user/personal/index'
                      })
                    }
                  }
                })
              }else if(userInfo.isRegister && parseInt(userInfo.isRegister)===0){
                //获取微信授权，但没注册成为注册用户的情况
                wx.showModal({
                  title: '温馨提示',
                  content: '您还未完成注册，请完成注册后重试',
                  confirmText: '前往注册',
                  success: res => {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '/pages/user/registerUser/index'
                      })
                    }
                  }
                })
              }else if(userInfo.isDriver && parseInt(userInfo.isDriver)===-1){
                //注册用户完成，但没完成会员信息录入的情况
                wx.showModal({
                  title: '温馨提示',
                  content: '您还未完成司机认证，请完成认证后重试',
                  confirmText: '前往认证',
                  success: res => {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '/pages/user/memberRegister/before'
                      })
                    }
                  }
                })
              }else{
                callback()
              }
          } else {
            //查询不到信息的情况
            wx.showModal({
              title: '温馨提示',
              content: '您还未完成注册，请完成注册后重试',
              confirmText: '前往注册',
              success: res => {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/user/personal/index'
                  })
                }
              }
            })
          }
        }
      },

    /**获取用户信息 */
    getUserInfo() {
        let userInfo = getApp().globalData.userInfo
        console.log(userInfo)
        this.setData({
            userInfo: userInfo
        })
    },

    /**获取工单列表 */
    getWorkOrderList() {
        if (!this.data.openid) {
            this.setData({
                spinShow: true
            })
            setTimeout(() => {
                let openid = getApp().getUserOpenid()
                this.setData({
                    openid
                })
                this.getWorkOrderList()
            }, 1000)
            return
        } else {
            if (this.data.spinShow) {
                this.setData({
                    spinShow: false
                })
            }
        }
        let param = {
            "openid": this.data.openid,
            "status": this.data.orderCurrentTag
        }
        requestUtil.postRequest(urls.workOrder.getOrderList + '?currentpage=1&&pagesize=50', param, (res) => {
            console.log(res)
            this.setData({
                orderList: res.list
            })
        }, () => {})
        // this.getInsuranceOrderList(this.data.insuranceListQuery, '')
        // if (this.data.insuranceList.length === 0) {
        // }
        // this.getAccidentReportList(this.data.accidentListQuery, '')
        // this.getAccidentReportList(['3','4', '6'], '')
        // if (this.data.accidentList.length === 0) {
        // }
    },
    /**跳转更多列表 */
    goToOrderList() {
        wx.navigateTo({
            url: '/pages/workOrder/list/index'
        })
    },
    /**
     * 处理工单点击事件
     * @param {*} e
     */
    handleClickWorkOrder(e) {
        let _orderId = e.detail.id
        let _orderSource = e.detail.from
        let _orderNo = e.detail.orderNo
        if (this.data.orderCurrentTag === '-1') {
            //
            wx.navigateTo({
                url: `/pages/workOrder/orderComplete/index?oid=${_orderId}&&from=${_orderSource}&&ono=${_orderNo}`
            })
        } else {
            wx.navigateTo({
                url: '/pages/workOrder/orderProcess/index?orderid=' + _orderId
            })
        }
    },

    /**处理服务订单列表筛选Tab */
    handelInsuranceListTab(e) {
        let index = e.detail.index
        if (index === 0) {
            this.data.insuranceListQuery = ['0', '1', '5']
            this.getInsuranceOrderList(this.data.insuranceListQuery, '')
        } else if (index === 1) {
            this.data.insuranceListQuery = ['4', '6']
            this.getInsuranceOrderList(this.data.insuranceListQuery, '')
        } else {
            this.data.insuranceListQuery = ['7', '8']
            this.getInsuranceOrderList(this.data.insuranceListQuery, '')
        }
    },

    /**获取服务订单列表 */
    getInsuranceOrderList(statusList, insuranceType) {
        if (!this.data.openid) {
            this.setData({
                spinShow: true
            })
            setTimeout(() => {
                let openid = getApp().getUserOpenid()
                this.setData({
                    openid
                })
                this.getInsuranceOrderList(statusList, insuranceType)
            }, 1000);
        } else {
            if (this.data.spinShow) {
                this.setData({
                    spinShow: false
                })
            }
            let param = {
                "insuranceClassifyId": insuranceType,
                "openid": this.data.openid,
                "orderStatusList": statusList
            }
            requestUtil.postRequest(urls.insurance.listOrder, param, (res) => {
                this.setData({
                    insuranceList: res.list
                })
            }, () => {})
        }
    },

    /**处理事故上报列表筛选Tab */
    handelAccidentListTab(e) {
        let index = e.detail.index
        if (index === 0) {
            this.data.accidentListQuery = ['0', '1', '2']
            this.getAccidentReportList(this.data.accidentListQuery, '')
        } else {
            this.data.accidentListQuery = ['3', '4', '6']
            this.getAccidentReportList(this.data.accidentListQuery, '')
        }
    },

    /**获取事故订单列表 */
    getAccidentReportList(statusList, insuranceType) {
        let param = {
            "insuranceClassifyId": insuranceType,
            "openid": this.data.openid,
            "accidentStatusList": statusList
        }
        requestUtil.postRequest(urls.accident.accidentList, param, (res) => {
            res.list.forEach((item) => {
                item.insuranceType = getApp().getInsuranceTypeKey(item.insuranceClassifyId)
            })
            this.setData({
                accidentList: res.list
            })
        }, () => {})
    },
    /**处理服务订单列表筛选Tab */
    handelTransportConfirmListTab(e) {
        let index = e.detail.index
        //console.log('====',index)
        this.getTransportConfirmList(index)
    },
    /**获取我的确认单列表 */
    getTransportConfirmList(status) {
        if (!this.data.openid) {
            this.setData({
                spinShow: true
            })
            setTimeout(() => {
                let openid = getApp().getUserOpenid()
                this.setData({
                    openid
                })
                this.getTransportConfirmList(status)
            }, 1000);
        } else {
            if (this.data.spinShow) {
                this.setData({
                    spinShow: false
                })
            }
            let param = {
                "openid": this.data.openid,
                "page": this.DEFAULT_PAGE,
                "rows": this.DEFAULT_SIZE
            }
            if (status || status == 1) {
                param.isArbitrate = status
            }
            requestUtil.postRequest(urls.transportConfirm.list, param, (res) => {
                this.setData({
                    transportConfirmList: res.list,
                    transportConfirmListCount: res.total
                })
            }, () => {})
        }
    },
    /**跳转更多列表 */
    goToTransportList() {
        wx.navigateTo({
            url: '/pages/transportConfirm/list/index'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.error(options)
        //获取分销码并全局缓存
        let _distributeCode = options.scene || ''
        getApp().saveDistributeCode(_distributeCode)
        console.log('_distributeCode', _distributeCode)
        console.log('options', options)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.checkUserInfoRole(()=>this.getUserInfo());
        switch (this.data.currentTab) {
            case 'tab1':
                this.getWorkOrderList()
                break;
            case 'tab2':
                this.getInsuranceOrderList(this.data.insuranceListQuery)
                break;
            case 'tab3':
                this.getAccidentReportList(this.data.accidentListQuery)
                break;
            case 'tab4':
                this.getTransportConfirmList(0);
            case 'tab6':
                this.getRescueApplyOrderList();
                case 'tab7':
                    this.getComplaintOrderList();
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            imageUrl: '/assets/share-bg.png'
        }
    }
})